package com.ruoyi.project.system.v.stream;

import com.ruoyi.project.system.v.config.RtmpConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Component
public class StreamPusher {

    @Autowired
    private RtmpConfig rtmpConfig;

    public void startStreaming() throws IOException {
        String inputFilePath = rtmpConfig.getInputFilePath();
        String rtmpUrl = rtmpConfig.getServer();

        // 构建 FFmpeg 命令
        String[] command = {
                "ffmpeg",
                "-re",
                "-i", inputFilePath,
                "-vcodec", "libx264",
                "-acodec", "aac",
                "-c", "copy",
                "-flvflags", "no_duration_filesize",
                "-f", "flv",
                "-safe", "0",
                rtmpUrl
        };

        // 使用 ProcessBuilder 执行命令
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        // 读取 FFmpeg 输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        // 处理错误输出
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while ((line = errorReader.readLine()) != null) {
            System.err.println(line);
        }

        // 等待进程结束
        try {
            int exitCode = process.waitFor();
            System.out.println("FFmpeg exited with code " + exitCode);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
